<template>
    <div>
        <el-card>
            <div>
                <el-button @click="addRoler" type="primary" icon="el-icon-circle-plus" circle size="mini">
                </el-button>
            </div>
            <el-table ref="multipleTable" :data="docs" tooltip-effect="dark" style="width: 100%">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column label="角色名" width="180">
                    <template slot-scope="scope">{{ scope.row.name }}</template>
                </el-table-column>
                <el-table-column prop="comments" label="角色描述" width="width">
                </el-table-column>
                <el-table-column label="操作" show-overflow-tooltip width="300">
                    <template slot-scope="{row,$index}">
                        <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="fixRoler(row)">
                        </el-button>
                        <el-button type="warning" icon="el-icon-s-data" circle size="mini" @click="setCheckedKeys(row)">
                        </el-button>
                        <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="open(row)">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- //分页器 -->
            <div style="display:table;margin:0 auto;margin-top:10px">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page.sync="pageInfo.current" :page-sizes="[2, 5, 8]" :page-size="pageInfo.pageSize"
                    layout="total,sizes, prev, pager, next" :total="pageInfo.totalItems"></el-pagination>
            </div>
        </el-card>
        <!-- //对话框1 -->
        <el-dialog :title="title" :visible.sync="dialogVisible" width="50%">
            <el-form :model="ruleForm" ref="ruleForm" :rules="rules" label-width="80px" :inline="false" size="normal">
                <el-form-item label="角色名" type="text" prop="name">
                    <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" type="text" prop="comments">
                    <el-input v-model="ruleForm.comments"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button v-if="styleSc == 1" type="primary" @click="submitForm('ruleForm')">保存</el-button>
                    <el-button v-else type="primary" @click="submitForm('ruleForm')">更新</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- //树形控件 -->
        <el-dialog title="分配资源" :visible.sync="dialogVisibleTree" width="30%">
            <el-tree node-key="_id" :data="treeList" :props="props" show-checkbox @check-change="getCheckedKeys"
                ref="tree">
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleTree = false">取 消</el-button>
                <el-button type="primary" @click="upDateNode">确 定</el-button>
            </span>
            <!-- <el-button @click="getCheckedKeys">通过 key 获取</el-button> -->
        </el-dialog>


    </div>
</template>

<script>
import {
    reqadminGroup, reqGetListTree, reqKeyList, reqAddOne, reqadminGroupPage,
    reqUpdateOne, reqDeleteGroup, reqUpdateNode
} from '@/api/adminGroup'
import { renderTreeData } from '@/utils/auth'
export default {
    name: 'adminGroup',
    data() {
        return {
            title: '',
            styleSc: '',
            scene: 1,
            form: [],
            value: '',
            //树形图数据
            dialogVisibleTree: false,
            dialogVisible3: false,
            //更新需要传入的数据
            row1: {},
            treeList: [],
            props: {
                label: 'comments',
                children: 'children'
            },
            count: 1,
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            //对话框
            dialogVisible: false,
            docs: [],
            pageInfo: {
                current: 1,
                pageSize: 10,
                searchkey: "",
                total: 0,
                // totalPage: 1
            },
            ruleForm: {
                name: '',
                comments: '',
                enable: false,
                power: [],
                _id: '',
                __v: '',
                date: ''
            },

            rules: {
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '输入长度在2到10之间', trigger: 'blur' },

                ],
                comments: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 5, max: 30, message: '输入长度在5到30之间', trigger: 'blur' },

                ],

            },
            multipleSelection: []
        }

    },
    mounted() {
        //请求用户组数据
        this.getAdminGroup()
        //获取资源数据
        // this.getListByPower()
        //获取属性图资源数据
        this.getListTree()
        //收集选中节点id
        // this.getCheckedKeys()
    },
    methods: {
        //请求用户组数据
        async getAdminGroup(pages = 1) {
            this.pageInfo.current = pages
            let result = await reqadminGroup()
            this.docs = result.data.docs
            this.pageInfo = result.data.pageInfo
            // console.log(result.data.pageInfo, '111');
        },
        //修改角色
        async fixRoler(row) {
            console.log(row);
            let result = await reqKeyList({ id: row._id })
            this.scene = 2
            this.dialogVisible = true
            this.styleSc = 2
            this.title = '修改角色信息'
            this.ruleForm = { ...result.data }
            console.log(this.ruleForm);
        },
        //删除角色
        async deleteGroup() {
            let result = await reqDeleteGroup()
            if (result.status == 200) {
                this.$message({ type: 'success', message: '删除成功' })
                this.getAdminGroup()
            }
        },
        //删除确认弹框
        open(row) {
            this.$confirm('您确认要删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                reqDeleteGroup({ ids: row._id }).then((res) => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    //请求用户组数据
                    this.getAdminGroup()
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //添加角色
        addRoler() {
            this.ruleForm = {}
            this.dialogVisible = true
            this.styleSc = 1
            this.title = '填写角色信息'
        },
        submitForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    if (this.styleSc == 1) {
                        const { name, comments, enable } = this.ruleForm
                        let result = await reqAddOne({ name, comments, enable })
                        if (result.status == 200) {
                            this.$message({ type: 'success', message: '添加成功' })
                            this.dialogVisible = false
                            this.getAdminGroup()
                        }
                    } else {
                        //修改角色
                        let result = await reqUpdateOne({ ...this.ruleForm })
                        if (result.status == 200) {
                            this.$message({ type: 'success', message: '更新成功' })
                            this.ruleForm = {}
                            this.dialogVisible = false
                            this.getAdminGroup()
                        }
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //挂载时获取资源数据
        async getListTree() {
            let result = await reqGetListTree()
            this.treeList = renderTreeData(result.data.docs)
            console.log(this.treeList)
        },
        //默认选中
        async setCheckedKeys(row) {
            this.dialogVisibleTree = true
            let result = await reqKeyList({ id: row._id })
            let power = result.data.power
            // console.log(power)
            this.$refs.tree.setCheckedKeys(power);
            //  this.$refs.tree.setCheckedKeys([3]);
            this.row1 = row
        },
        //获取节点
        getCheckedKeys() {
            console.log(this.$refs.tree.getCheckedKeys());
            let power = this.$refs.tree.getCheckedKeys()
            this.row1.power = power
            // console.log(this.row1);
        },
        //更新节点
        async upDateNode() {
            this.dialogVisibleTree = false
            let result = await reqUpdateNode(this.row1)
            if (result.status == 200) {
                this.$message({ type: 'success', message: '权限分配成功' })
            } else {
                return Promise.reject(new Error('faile'))
            }
            this.getAdminGroup()
        },
        //分页
        async renderPageList(current = 1, pageSize = 10) {
            let searchkey = this.pageInfo ? this.pageInfo.searchkey : "";
            let state = this.pageInfo ? this.pageInfo.state : "";
            let user = this.pageInfo ? this.pageInfo.user : "";
            let targetCurrent = current;
            let result = await reqadminGroupPage({
                current: targetCurrent,
                pageSize,
                searchkey
            });
            this.docs = result.data.docs
            //ComponentPaginationEnd
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            let current = this.pageInfo ? this.pageInfo.current : 1;
            this.renderPageList(current, val);
            this.pageInfo.pageSize=val
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            let pageSize = this.pageInfo ? this.pageInfo.pageSize : 10;
            this.renderPageList(val, pageSize);
        }

    },

}
</script>

<style>
</style>